//
//  CZQCyclePublishVC.m
//  coachmanage
//
//  Created by 众拳科技 on 2018/3/23.
//  Copyright © 2018年 众拳科技. All rights reserved.
//

#import "CZQCyclePublishVC.h"
#import "CZQCustonTextView.h"
#import "DHCustomImageView.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <MediaPlayer/MediaPlayer.h>
@interface CZQCyclePublishVC ()<SDPhotoBrowserDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    
    //调用相机照相，摄影
    UIImagePickerController *_imagePickerController;
    
    NSData *_data;
   
}

/**
 输入文字
 */
@property(nonatomic,weak)CZQCustonTextView *textView;

/**
 当前位置
 */
@property(nonatomic,weak)UIButton *addressBtn;

 //高清图
@property(nonatomic,strong)NSMutableArray *imgRefArrM;

//存放URLString
@property(nonatomic,strong)NSMutableArray *urlStringArrM;

//放图片的

@property(nonatomic,strong)UIView *picView;


/**
 视频图片地址
 */
@property(nonatomic,strong)NSString *urlString;

@end

@implementation CZQCyclePublishVC

-(NSMutableArray *)imgRefArrM
{
    if (!_imgRefArrM) {
        _imgRefArrM = [NSMutableArray array];
    }
    return _imgRefArrM;
}

-(NSMutableArray *)urlStringArrM
{
    if (!_urlStringArrM) {
        _urlStringArrM = [NSMutableArray array];
    }
    return _urlStringArrM;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"发布动态";
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self creatSubviews];
    
}

-(void)creatSubviews
{
    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"发布" style:UIBarButtonItemStylePlain target:self action:@selector(publish)];
    [rightButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:CSBlackColor,NSFontAttributeName:MidFont} forState:UIControlStateNormal];
    [rightButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:CSBlackColor,NSFontAttributeName:MidFont} forState:UIControlStateHighlighted];
    
    self.navigationItem.rightBarButtonItem = rightButtonItem;
    
    CZQCustonTextView *custText = [CZQCustonTextView new];
    custText.placeLable.text = @"此时此刻的想法....";
    [self.view addSubview:custText];
    self.textView = custText;
    
    [custText mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.top.left.right.mas_equalTo(self.view);
        
        make.height.mas_equalTo(150);
        
    }];
    
    //地址
    UIButton *addressBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [addressBtn setTitleColor:GrakColor];
    [addressBtn setTitle:@"九江市"];
    addressBtn.titleLabel.font = MidFont;
    [addressBtn setImage:@"icon_coordinate"];
    [addressBtn setImageEdgeInsets:UIEdgeInsetsMake(0, -2, 0, 0)];
    [self.view addSubview:addressBtn];
    self.addressBtn = addressBtn;
    
    [addressBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.textView.mas_bottom).offset(5);
        make.left.mas_equalTo(self.view.mas_left).offset(10);
        
    }];
    
    //切换地址
    UIButton *choseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [choseBtn setTitleColor:BlackColor];
    [choseBtn setTitle:@"切换"];
    choseBtn.titleLabel.font = MidBigFont;
    [self.view addSubview:choseBtn];
    
    UIView *sepview = [UIView new];
    sepview.backgroundColor = [UIColor blackColor];
    [choseBtn addSubview:sepview];
    
    [choseBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.mas_equalTo(self.addressBtn);
        make.left.mas_equalTo(self.addressBtn.mas_right).offset(10);
        
    }];
    [sepview mas_remakeConstraints:^(MASConstraintMaker *make) {

        make.centerX.mas_equalTo(choseBtn);
        make.bottom.mas_equalTo(choseBtn).offset(-2);
        make.height.mas_equalTo(2);
        make.width.mas_equalTo(choseBtn);
    }];
    
    
    
    //添加图片
    
    CGFloat itemW = (kScreenWidth - 60)/5;
    _picView = [[UIView alloc]init];
    _picView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_picView];
    [_picView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.addressBtn.mas_bottom).offset(20);
        make.left.mas_equalTo(self.view.mas_left).offset(0);
        make.right.mas_equalTo(self.view.mas_right).offset(0);
        make.height.mas_equalTo(itemW + 20);
    }];
    
    [self creatAddPhotoView];
    
    
}

-(void)creatAddPhotoView
{
    
    [_picView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    //每行几个
    NSInteger rowCount = 4;
    CGFloat itemW = (kScreenWidth - (rowCount + 1)*10)/rowCount;
    for (int i = 0; i < _imgRefArrM.count; i++) {
        DHCustomImageView *photoView = [[DHCustomImageView alloc]initWithFrame:CGRectMake( 10 + i%rowCount * (itemW + 10),10 + i/rowCount *(itemW + 10), itemW, itemW)];
        photoView.userInteractionEnabled  = YES;
        
        
        [_picView addSubview:photoView];
        photoView.tag = i;
        if (_isVideo == YES ) {
            
            photoView.image = PlaceHold;
            
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                // 处理耗时操作的代码块...
                
                UIImage *image = [Helper thumbnailImageForVideo:_imgRefArrM[i] atTime:1];
                //通知主线程刷新
                dispatch_async(dispatch_get_main_queue(), ^{
                    //回调或者说是通知主线程刷新，
                    
                    photoView.image = image;
                });
                
                
                
            });
            
            UIButton *playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            
            
            
            //            playBtn.contentEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
            
            [playBtn setImage:[UIImage imageNamed:@"icon_video"] forState:UIControlStateNormal];
            
            [playBtn addTarget:self action:@selector(playVideo) forControlEvents:UIControlEventTouchUpInside];
            
            [photoView addSubview:playBtn];
            
            [playBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.top.mas_equalTo(photoView).offset(10);
                make.right.bottom.mas_equalTo(photoView).offset(-10);
            }];
            

        
        }else
            
        {
            photoView.image = [UIImage imageWithData:_imgRefArrM[i]];
            
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapImageView:)];
            [photoView addGestureRecognizer:tap];
        }
        
        
        photoView.deleteBtn.tag = 100 + i;
        [photoView.deleteBtn addTarget:self action:@selector(deleteImage:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    
    //有几行图片
    NSInteger row = (_imgRefArrM.count )/rowCount;
    [_picView  mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.height.mas_equalTo((itemW + 10) * (row +1)+ 10);
    }];
    
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addBtn.frame = CGRectMake(10 +_imgRefArrM.count%rowCount* (itemW + 10),10 + _imgRefArrM.count/rowCount *(itemW +10), itemW, itemW);
    //    addBtn.backgroundColor = [UIColor redColor];
    [addBtn setImage:[UIImage imageNamed:@"inon_adds"] forState:UIControlStateNormal];
    [addBtn addTarget:self action:@selector(addPhoto:) forControlEvents:UIControlEventTouchUpInside];
    if (_imgRefArrM.count == 9  || _isVideo == YES) {
        addBtn.hidden = YES;
        
        if (_isVideo == YES && _imgRefArrM.count == 0) {
            addBtn.hidden = NO;
        }
    }
    [_picView addSubview:addBtn];
}

#pragma Logo图片选择
-(void)addPhoto:(UIButton *)photoSelect{
    
    [JHSysAlertUtil presentAlertWithTitle:nil message:nil actionTitles:@[@"拍摄",@"从手机相册选择图片"] preferredStyle:UIAlertControllerStyleActionSheet handler:^(NSUInteger buttonIndex, NSString *buttonTitle) {
        if (buttonIndex == 1) {
            
            //创建UIImagePickerController对象
            _imagePickerController = [[UIImagePickerController alloc]init];
            _imagePickerController.delegate = self;
            _imagePickerController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
            _imagePickerController.allowsEditing = YES;
            _imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            
            //是否可编辑
            //录制视频时长，默认10s
            _imagePickerController.videoMaximumDuration = 10;
            
            if (_isVideo) {
                _imagePickerController.mediaTypes =  [[NSArray alloc] initWithObjects:(NSString *) kUTTypeMovie, nil];
            }else
            {
                _imagePickerController.mediaTypes =  [[NSArray alloc] initWithObjects:(NSString *) (NSString *) kUTTypeImage, nil];
                
            }
            
            
//            _imagePickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
            
            
            [self presentViewController:_imagePickerController animated:YES completion:nil];
        }
        else if (buttonIndex == 2 || buttonIndex == 3 )
        {
            
            WS(weakSelf);
            
            ZLPhotoPickerViewController *pickerVc = [[ZLPhotoPickerViewController alloc] init];
            
            //    pickerVc.maxCount = 1;
            
            // Jump AssetsVc
            pickerVc.status = PickerViewShowStatusCameraRoll;
            // Recoder Select Assets
            //    pickerVc.selectPickers = self.assets;
            // Filter: PickerPhotoStatusAllVideoAndPhotos, PickerPhotoStatusVideos, PickerPhotoStatusPhotos.
            
            if (self.isVideo) {
                pickerVc.maxCount = 1;
                pickerVc.photoStatus = PickerPhotoStatusVideos;
            }else
            {
                pickerVc.maxCount = 9 - weakSelf.imgRefArrM.count;
                pickerVc.photoStatus = PickerPhotoStatusPhotos;
            }
            //    pickerVc.photoStatus = PickerPhotoStatusAllVideoAndPhotos;
            
            // Desc Show Photos, And Suppor Camera
            //    pickerVc.isShowCamera = YES;
            pickerVc.topShowPhotoPicker = YES;
            
            // CallBack
            
            pickerVc.callBack = ^(NSArray<ZLPhotoAssets *> *status){
                
                for (ZLPhotoAssets *assets in status) {
                    
                    ZLPhotoPickerBrowserPhoto *photo = [ZLPhotoPickerBrowserPhoto photoAnyImageObjWith:assets];
                    
                    photo.asset = assets;
                    
                    UIImage *image;
                    
                    if (weakSelf.isVideo) {
                        
                        
                        NSData *videoData = [NSData dataWithContentsOfURL:assets.assetURL];
                        
                        [weakSelf.imgRefArrM removeAllObjects];
                        
                        
                        [weakSelf.imgRefArrM addObject:assets.assetURL];
                        
                        [weakSelf uploadImage:videoData];
                        
                    }else
                    {
                        
                        //拍照
                        if ([photo.asset isKindOfClass:[UIImage class]]) {
                            
                            image = (UIImage *)photo.asset;
                            
                        }
                        else{
                            
                            image = [assets thumbImage];
                            
                            
                        }
                        
                        NSData *imageData = [Helper scaleImage:image toKb:100];
                        
                        [weakSelf.imgRefArrM addObject:imageData];
                        
                        [weakSelf uploadImage:imageData];
                        
                    }
                    
                    
                    
                    
                }
                
                [weakSelf creatAddPhotoView];
            };
            
            [pickerVc showPickerVc:self];
            
            
        }
    }];
    
    
}

//适用获取所有媒体资源，只需判断资源类型
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    //判断资源类型

    WS(weakSelf);
    
    
    NSString *mediaType=[info objectForKey:UIImagePickerControllerMediaType];
    //判断资源类型
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]){
        //如果是图片
        UIImageView *img = [[UIImageView alloc]init];
        img.image = info[UIImagePickerControllerOriginalImage];
        //压缩图片
        
        NSData *imageData = [Helper scaleImage:img.image toKb:100];
        
        
        [weakSelf.imgRefArrM addObject:imageData];
        
        [weakSelf uploadImage:imageData];
        
        
        
    }else
    {
        
        
        
        [_imgRefArrM removeAllObjects];
        
        //如果是视频
        NSURL *url = info[UIImagePickerControllerMediaURL];
        NSURL *mp4 = [Helper _convert2Mp4:url];
        
        
        NSData *videoData = [NSData dataWithContentsOfURL:mp4];
        
        
        [_imgRefArrM addObject:mp4];
        
        [weakSelf uploadImage:videoData];
    }
    
        
    [self creatAddPhotoView];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];//退出
}

-(void)playVideo
{
    
    // 设置视频播放器
    MPMoviePlayerViewController *moviePlayerController = [[MPMoviePlayerViewController alloc] initWithContentURL:[_imgRefArrM lastObject]];
    
    [moviePlayerController.moviePlayer prepareToPlay];
    moviePlayerController.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
    [self presentMoviePlayerViewControllerAnimated:moviePlayerController];
}

#pragma mark - 发布圈子
-(void)publish
{
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    
    [params setObject:[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"UserID"]] forKey:@"MemberID"];
    
    [params setObject:[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"MasterType"]] forKey:@"UserType"];
    
    [params setObject:[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"ShopID"]] forKey:@"ShopID"];
    
    NSString *title = self.textView.textView.text;
    
    [params setObject:title forKey:@"Title"];
    
    [params setObject:@"1" forKey:@"ViewCount"];
    
    [params setObject:@"九江市" forKey:@"Location"];
    
    self.urlString = [self.urlStringArrM componentsJoinedByString:@","];
    
    [params setObject:self.urlString forKey:@"Pics"];
    
    NSLog(@"%@",self.urlString);
    
    
    [MBProgressHUD showMessage:@"请求中..." toView:self.view];
    
    
    
    [HTTPTool POSTRaw:Post_Activity_Operate parameters:params

              success:^(id responseObject){

                  [MBProgressHUD hideHUDForView:self.view];

                  if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {

                      [MBProgressHUD showText:@"发布成功"];


                      [self.navigationController popViewControllerAnimated:YES];

                      [MBProgressHUD hideHUDForView:self.view];
                  }

              }

              failure:^(NSError *error){

                  [MBProgressHUD hideHUDForView:self.view];
              }];
    
}
    
#pragma mark 上传头像
-(void)uploadImage:(NSData *)data{
    

    WS(weakSelf);
    
//    imageData  = UIImageJPEGRepresentation(image,0.1);
    
    [MBProgressHUD showMessage:@"上传中.." toView:self.view];
    
    RAYUploader *upload = [RAYUploader defaultUploader];
    
    [upload uploadWithData:data isvideo:self.isVideo  complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        
        [MBProgressHUD hideHUDForView:weakSelf.view];
        
        if (key) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                NSString *picUrl = [NSString stringWithFormat:@"%@%@",QiNiuBase,key];
                
                [weakSelf.urlStringArrM addObject:picUrl];
                
            });
            
        }
        
    }];
    
}


- (void)tapImageView:(UITapGestureRecognizer *)tap
{
    UIView *imageView = tap.view;
    SDPhotoBrowser *browser = [[SDPhotoBrowser alloc] init];
    browser.currentImageIndex = imageView.tag;
    browser.sourceImagesContainerView = _picView;
    browser.imageCount = _imgRefArrM.count;
    browser.delegate = self;
    [browser show];
}

-(void)deleteImage:(UIButton *)sender
{
    [self.imgRefArrM removeObjectAtIndex:sender.tag - 100];
    
    [self.urlStringArrM removeObjectAtIndex:sender.tag - 100];
    
    [self creatAddPhotoView];
}

#pragma mark - SDPhotoBrowserDelegate

- (NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index
{
    //    _index = index;
    NSData *imageName = _imgRefArrM[index];
    NSURL *url = [NSURL URLWithString:[[NSString alloc]initWithData:imageName encoding:NSUTF8StringEncoding ]];
    //    NSURL *url = [[NSBundle mainBundle] URLForResource:imageName withExtension:nil];
    return url;
}

- (UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index
{
    //    UIImageView *imageView ;
    
    return [UIImage imageWithData:_imgRefArrM[index]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
